
package com.product.android.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.text.TextUtils;

import com.common.android.utils.SdCardUtils;

/**
 * 
 * Log相关工具类
 * <br>Created 2013-11-5下午5:58:10
 * @version  
 * @author   daiyf		
 *
 * @see 	 
 * 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 *
 */
public class LogUtils {
    private final static boolean logFlag = true;

    private final static int logLevel = android.util.Log.VERBOSE;
    public static String tag = "";
    private static LogUtils instance = null;
    
    //模块名称对应
    public static final String WB_LST = "WB_LST";  //微博列表
    public static final String WB_CMT = "WB_CMT";    //微博评论
    public static final String WB_CMPS = "WB_CMPS";  //发表微博
    public static final String WB_FLL = "WB_FLL";   //微博关注/粉丝
    public static final String WB_BLST = "WB_BLST";  //黑名单
    public static final String WB_STLV = "WB_STLV";    //暗恋管理
    public static final String WB_FLOW = "WB_FLOW";  //礼物管理
    public static final String WB_PTAG = "WB_PTAG";   //个性标签
    public static final String WB_PINF = "WB_PINF";   //个人资料
    public static final String WB_RANK = "WB_RANK";   //排行榜
    
    public static final String ALB_LST = "ALB_LST";  //相册列表
    public static final String ALB_BRS = "ALB_BRS";    //相册浏览
    public static final String ALB_CMT = "ALB_CMT";  //照片评论
    
    public static final String TFL_LST = "TFL_LST";  //群共享文件浏览
    public static final String FFL_UPLD = "FFL_UPLD";    //群共享文件上传
    
    public static final String M_FRIEND = "M_FRIEND";  //好友
    public static final String M_UNIT = "M_UNIT";    //组织
    public static final String M_GROUP = "M_GROUP";  //群组
    public static final String M_WATERFALL = "M_WATERFALL";   //照片墙    
    public static final String M_START = "M_START";  //启动
    public static final String M_APPGRID = "M_APPGRID";    //应用
    public static final String M_LOTTERY = "M_LOTTERY";  //抽奖
    public static final String M_SETTING = "M_SETTING";   //设置
    public static final String M_BLESS = "M_BLESS";  //生日祝福
    public static final String IM="IM";           //通讯
    public static final String CHAT = "CHAT";    //聊天模块
    
    public static final String HR = "HR";  //HR识人
    
    public static final String MARKET = "MARKET";   //二手市场
    
    public static final String TIMECOST = "TIMECOST";   //QA 要求的log收集    
    
    public static final String DB_ERROR="DB_ERROR";
    
    public static final int VERBOSE = android.util.Log.VERBOSE;
    // Field descriptor
    public static final int DEBUG = android.util.Log.DEBUG;
    // Field descriptor
    public static final int INFO = android.util.Log.INFO;
    // Field descriptor
    public static final int WARN = android.util.Log.WARN;
    // Field descriptor
    public static final int ERROR = android.util.Log.ERROR;
    // Field descriptor
    public static final int ASSERT = android.util.Log.ASSERT;
    
    private static LogUtils getInstance() {
        if (instance == null) {
            instance = new LogUtils();
        }
        return instance;
    }

    /**
     * 获取运行时信息
     * <br>Created 2014-8-22 下午3:04:00
     * @return 运行时信息
     * @author       huangyx
     */
    private String getFunctionName()
    {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();
        if (sts == null) {
            return null;
        }
        for (StackTraceElement st : sts) {
            // Log.d("a", "st:" + st.toString());
            if (st.isNativeMethod()) {
                continue;
            }
            if (st.getClassName().equals(Thread.class.getName())) {
                continue;
            }
            if (st.getClassName().equals(this.getClass().getName())) {
                continue;
            }
            tag = st.getClassName();
            return "[ " + Thread.currentThread().getName() + ": "
                    + st.getFileName() + ":" + st.getLineNumber() + " "
                    + st.getMethodName() + " ]";
        }
        return null;
    }

    /**
     * 打印INFO
     * <br>Created 2014-8-22 下午3:05:00
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void i(String msg)
    {
        i(null, msg);
    }

    /**
     * 打印INFO
     * <br>Created 2014-8-22 下午3:00:00
     * @param tag 日志标志
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void i(String tag, String msg) {
        i(tag, msg, null);
    }

    /**
     * 打印INFO
     * <br>Created 2014-8-22 下午3:07:00
     * @param tag 日志标志
     * @param msg 日志内容
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void i(String tag, String msg, Throwable tr)
    {
        if (logFlag)
        {
            if (logLevel <= android.util.Log.INFO)
            {
                String name = getInstance().getFunctionName();
                if (name != null)
                {
                    msg = new StringBuilder(name).append(" - ").append(msg).toString();
                }

                if (TextUtils.isEmpty(tag)) {
                    tag = LogUtils.tag;
                }

                if (tr == null) {
                    android.util.Log.i(tag, msg);
                } else {
                    android.util.Log.i(tag, msg, tr);
                }
            }
        }
    }

    /**
     * 打印DEBUG日志
     * <br>Created 2014-8-22 下午3:10:14
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void d(String msg)
    {
        d(null, msg);
    }

    /**
     * 打印DEBUG日志
     * <br>Created 2014-8-22 下午3:11:57
     * @param tag 日志标志
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void d(String tag, String msg)
    {
        d(tag, msg, null);
    }
    
    /**
     * 打印DEBUG日志
     * <br>Created 2014-8-22 下午3:12:30
     * @param tag 日志标志
     * @param msg 日志内容
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void d(String tag, String msg, Throwable tr)
    {
        if (logFlag)
        {
            if (logLevel <= android.util.Log.DEBUG)
            {
                String name = getInstance().getFunctionName();
                if (name != null)
                {
                    msg = new StringBuilder(name).append(" - ").append(msg).toString();
                }

                if (TextUtils.isEmpty(tag)) {
                    tag = LogUtils.tag;
                }

                if (tr == null) {
                    android.util.Log.d(tag, msg);
                } else {
                    android.util.Log.d(tag, msg, tr);
                }
            }
        }
    }

    /**
     * 打印VERBOSE日志
     * <br>Created 2014-8-22 下午3:13:57
     * @param tag 日志标志
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void v(String tag, String msg)
    {
        v(tag, msg, null);
    }

    /**
     * 打印VERBOSE日志
     * <br>Created 2014-8-22 下午3:14:30
     * @param tag 日志标志
     * @param msg 日志内容
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void v(String tag, String msg, Throwable tr)
    {
        if (logFlag&&!tag.equals(IM))
        {
            if (logLevel <= android.util.Log.VERBOSE)
            {
                String name = getInstance().getFunctionName();
                if (name != null)
                {
                    msg = new StringBuilder(name).append(" - ").append(msg).toString();
                }

                if (TextUtils.isEmpty(tag)) {
                    tag = LogUtils.tag;
                }
                if (tr == null) {
                    android.util.Log.v(tag, msg);
                } else {
                    android.util.Log.v(tag, msg, tr);
                }
            }
        }
    }

    /**
     * 打印WARN日志
     * <br>Created 2014-8-22 下午3:15:57
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void w(String msg)
    {
        w(null, msg);
    }

    /**
     * 打印WARN日志
     * <br>Created 2014-8-22 下午3:16:57
     * @param tag 日志标志
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void w(String tag, String msg)
    {
        w(tag, msg, null);
    }

    /**
     * 打印WARN日志
     * <br>Created 2014-8-22 下午3:17:30
     * @param tag 日志标志
     * @param msg 日志内容
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void w(String tag, String msg, Throwable tr)
    {
        if (logFlag)
        {
            if (logLevel <= android.util.Log.WARN)
            {
                String name = getInstance().getFunctionName();
                if (name != null)
                {
                    msg = new StringBuilder(name).append(" - ").append(msg).toString();
                }

                if (TextUtils.isEmpty(tag)) {
                    tag = LogUtils.tag;
                }

                if (tr == null) {
                    android.util.Log.w(tag, msg);
                } else {
                    android.util.Log.w(tag, msg, tr);
                }
            }
        }
    }

    /**
     * 打印ERROR日志
     * <br>Created 2014-8-22 下午3:18:30
     * @param tag 日志标志
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void e(String msg)
    {
        e(null, msg);
    }

    /**
     * 打印ERROR日志
     * <br>Created 2014-8-22 下午3:19:30
     * @param tag 日志标志
     * @param msg 日志内容
     * @author       huangyx
     */
    public static void e(String tag, String msg)
    {
        e(tag, msg, null);
    }

    /**
     * 打印ERROR日志
     * <br>Created 2014-8-22 下午3:20:30
     * @param tag 日志标志
     * @param msg 日志内容
     * @param tr 输出到日志的异常
     * @author       huangyx
     */
    public static void e(String tag, String msg, Throwable tr)
    {
        if (logFlag)
        {
            if (logLevel <= android.util.Log.ERROR)
            {
                String name = getInstance().getFunctionName();
                if (name != null)
                {
                    msg = new StringBuilder(name).append(" - ").append(msg).toString();
                }

                if (TextUtils.isEmpty(tag)) {
                    tag = LogUtils.tag;
                }
                if (tr == null) {
                    android.util.Log.e(tag, msg);
                } else {
                    android.util.Log.e(tag, msg, tr);
                }
            }
        }
    }

    /**
     * 日志写入到文件中
     * <br>Created 2014-8-22 下午3:49:27
     * @param ctx 上下文
     * @param strMsg 日志内容
     * @author       huangyx
     */
    public static void writeLogToFile(Context ctx, String strMsg) {
    	//这里千万不能崩啊
    	try{
    		// 加上 [时:分:秒]
        	Calendar calendarCur = Calendar.getInstance();
    		String strTime = new StringBuilder("[")
    				.append(new SimpleDateFormat("HH:mm:ss")
    						.format(calendarCur.getTime())).append("]").toString();

        	//加上运行时信息
    		String strFunName = getInstance().getFunctionName();
    		if (!TextUtils.isEmpty(strFunName)) {
    			strMsg = new StringBuilder(strTime).append(strFunName).append(" - ")
    					.append(strMsg).toString();
    		}else{
    			strMsg = new StringBuilder(strTime).append(strMsg).toString();
    		}
    		
    		final String LINE_SEPERATOR = "\r\n";
    		if(!strMsg.endsWith(LINE_SEPERATOR)){
    			strMsg += LINE_SEPERATOR;
    		}
    		
    		//获得文件
    		File fLog = getLogFileToWrite(ctx, calendarCur);
    		if(null == fLog){
    			return;
    		}
    		
    		//写入信息
    		FileOutputStream fos = null;
    		try {
    			fos = new FileOutputStream(fLog, true);			
    			byte[] bytes = strMsg.getBytes();
    			fos.write(bytes);
    		} catch (FileNotFoundException e) {
    		} catch (IOException e) {
    		}
    		
    		finally {
    			if (null != fos) {
    				try {
    					fos.close();
    				} catch (IOException e) {
    				}
    			}
    		}
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    }
    
    /**
     * 获取待写入的日志文件
     * <br>Created 2014-8-22 下午3:51:04
     * @param ctx 上下文
     * @param calendar 时间对象
     * @return 日志文件
     * @author       huangyx
     */
    private static File getLogFileToWrite(Context ctx, Calendar calendar){
		String strLogName = new StringBuilder(new SimpleDateFormat(
				"yyyy-MM-dd").format(calendar.getTime())).append(".log")
				.toString();
		    	
		//取得SD卡上的日志路径，如果无SD卡，返回内部存储的日志路径
		
		String strDir = SdCardUtils.getSDCardCacheDir(ctx);
		StringBuilder sbDir = new StringBuilder(null == strDir ? "" : strDir);
		if(0 == sbDir.length()){
			sbDir.append(SdCardUtils.getInternalStoreCacheDir(ctx));	
		}
		
		if(0 == sbDir.length()){
			return null;
		}
		
		strDir =  sbDir.append("Log").append(File.separator).toString();
		
		//得到日志文件夹路径
		File fLogDir = new File(strDir);
		if(!fLogDir.exists()){
			fLogDir.mkdirs();				
		}
		
		//返回文件
		File fLog = new File(strDir + strLogName);
		if (!fLog.exists()) {
			try {
				fLog.createNewFile();
			} catch (IOException e) {
				return null;
			}
		}
		return fLog;
    }
}
